/**
 * 待发货
 * 
 * @return {}
 */
var orderToBeSend = new Ext.LoadMask(Ext.getBody(), {
			msg : "正在提交,请稍后..."
		});
var queryOrderToBeSendSearch = function() {
	var queryOrdersToBeSendFieldSet = new Ext.form.FieldSet({
				id : 'queryOrdersToBeSendFieldSet',
				title : '查询条件',
				collapsible : true,// 可折叠
				buttonAlign : 'center',
				buttons : [{
					text : '查询',
					handler : function() {
						queryOrdersToBeSend();
					}
				}, {
					text : '重置',
					handler : function() {
						Ext.getCmp('queryOrderToBeSendForm').getForm()
								.reset();
					}
				}],
				keys : [{
							key : 13, // 13代表回车
							fn : queryOrdersToBeSend,
							scope : this
						}],
				items : [{
					layout : 'column',
					border : false,
					items : [{
								columnWidth : .25,
								layout : 'form',
								border : false,
								items : [{
											xtype : 'textfield',
											name : 'id',
											anchor : '100%',
											fieldLabel : '订单编号'
										}]
							}, {
								columnWidth : .25,
								layout : 'form',
								border : false,
								items : [{
											xtype : 'textfield',
											anchor : '100%',
											fieldLabel : '订单编码',
											name : "orderCode"
										}]
							}, {
								columnWidth : .25,
								layout : 'form',
								border : false,
								items : [{
											xtype : 'textfield',
											anchor : '100%',
											fieldLabel : '物流公司电话',
											name : "shipperPhone"
										}]
							}, {
								columnWidth : .25,
								layout : 'form',
								border : false,
								items : [{
											xtype : 'textfield',
											anchor : '100%',
											fieldLabel : '物流公司名称',
											name : "shipperCodeName"
										}]
							}]
				}]
			});
	fieldSetListeners(['queryOrdersToBeSendFieldSet',
					'queryOrderToBeSendForm', 'orderVfManagerGrid'],
			[0.23, 0.77]);

	var queryOrderToBeSendForm = new Ext.form.FormPanel({
				id : 'queryOrderToBeSendForm',
				anchor : '100% 20%',
				frame : true,
				labelAlign : 'right',
				bodyBorder : false,
				items : [queryOrdersToBeSendFieldSet]
			});
	return queryOrderToBeSendForm;
};

/**
 * grids
 */
var orderToBeSendManagerGrid = function() {
	var orderToBeSendSm = new Ext.grid.CheckboxSelectionModel({
		checkOnly : true,
				renderer : function(v, p, record) {
					var logisticNo = record.get('logisticNo');
					if (logisticNo != '') {
						return '<div class="x-grid3-row-checker">&#160;</div>';
					} else {
						return '';
					}
				},
				listeners : {
					beforerowselect : function(SelectionModel, rowIndex,
							keepExisting, record) {
						var logisticNo = record.get('logisticNo');
						if (logisticNo != '') {
							return true;
						} else {
							return false;
						}
					}
				}
			});
	// 定义表的每列（对应表头信息）
	var orderToBeSendCm = new Ext.grid.ColumnModel([orderToBeSendSm, {
				dataIndex : "id",
				header : "订单编号",
				sortable : false,
				width : 60
			}, {
				dataIndex : "orderCode",
				header : "订单编码",
				sortable : false,
				width : 160,
				renderer : function(value, cellmeta, record, rowIndex,
						columnIndex, store) {
					var returnValue = "";
					var orderId = record.data.id;
					if (value) {
						returnValue = '<a href ="#" onClick="lookOrderToBeSendDetail(\''
								+ orderId + '\')">' + value + '</a>';
					}
					return returnValue;
				}
			}, {
				dataIndex : "orderType",
				header : "订单类型",
				sortable : false,
				width : 70,
				renderer : function(value) {
					return PmsUtil.OrderType(value);
				}
			}, {
				dataIndex : "orderStatus",
				header : "订单状态",
				sortable : false,
				width : 60,
				renderer : function(value) {
					if (value) {
						return '<font color=\"#FF0000\" >'
								+ PmsUtil.OrderVfStatus(value) + '</font>';
					}
				}
			}, {
				dataIndex : "payAmount",
				header : "订单金额",
				sortable : false,
				width : 70,
				renderer : function(value) {
					return Ext.util.Format.number(value, '0,0.00');
				}
			}, {
				dataIndex : "goodsNumber",
				header : "商品数量",
				sortable : false,
				width : 60
			},{
				dataIndex : "payStatus",
				header : "支付状态",
				sortable : false,
				width : 60,
				renderer : function(value) {
					return PmsUtil.OrderPayStatus(value);
				}
			}, {
				dataIndex : "logisticNo",
				header : "物流单号",
				sortable : false,
				width : 100
			},{
				dataIndex : "shipperCode",
				header : "物流公司编码",
				sortable : false,
				width : 100
			}, {
				dataIndex : "shipperCodeName",
				header : "物流公司名称",
				sortable : false,
				width : 100
			}, {
				dataIndex : "shipperPhone",
				header : "物流公司电话",
				sortable : false,
				width : 100
			}, {
				dataIndex : "consignee",
				header : "收货人",
				sortable : false,
				width : 70
			}, {
				dataIndex : "consignPhone",
				header : "收货人电话",
				sortable : false,
				width : 100
			}, {
				dataIndex : "consignAddress",
				header : "收货人地址",
				sortable : false,
				width : 180,
				renderer : function(value, meta, record) {
					if (value) {
						meta.attr = 'ext:qtitle="收货人地址:" ext:qtip="' + value
								+ '"';
						return value;
					}
				}
			}, {
				dataIndex : "createdDate",
				header : "创建时间",
				sortable : false,
				width : 130
			}, {
				dataIndex : "remark",
				header : "备注",
				sortable : false,
				width : 100,
				renderer : function(value, meta, record) {
					if (value) {
						meta.attr = 'ext:qtitle="备注:" ext:qtip="' + value + '"';
						return '<font color=\"#FF0000\" >' + value + '</font>';
					}
				}
			}, {
				header : "管理",
				width : 250,
				dataIndex : "id",
				renderer : function(j, i, g, m, h) {
					var orderId = g.data.id;
					var orderStatus = g.data.orderStatus;
					var logisticNo = g.data.logisticNo;
					var k = "";
					if (orderStatus == 1 && logisticNo!="" && isGranted("orderToBeSend_单个发货")) {
						k += '&nbsp;&nbsp;<a href="#" onclick="updateOrderToBeSendStatusOne('
								+ orderId
								+ ','
								+ "2"
								+ ','
								+ "'已发货'"
								+ ')\">订单发货</a>';
					}
					if (orderStatus == 1 && isGranted("orderToBeSend_修改订单")) {
						k += '&nbsp;&nbsp;<a href="#" onclick="updateOrderToBeSend('
								+ orderId + ')\">修改订单</a>';
					}
					if (orderStatus == 1 && isGranted("orderToBeSend_订单详情")) {
						k += '&nbsp;&nbsp;<a href="#" onclick="lookOrderToBeSendDetail('
								+ orderId + ')\">订单详情</a>';
					}
					if (orderStatus == 1 && isGranted("orderToBeSend_填写物流单号")) {
						k += '&nbsp;&nbsp;<a href="#" onclick="addLogisticNo('
								+ orderId + ')\">填写物流单号</a>';
					}
					return k;
				}
			}]);
	// 定义分析器
	var orderManagerReader = new Ext.data.JsonReader({
				totalProperty : "totalCount",
				root : "list",
				fields : [{
							name : "id"
						}, {
							name : "orderCode"
						}, {
							name : "userId"
						}, {
							name : "userName"
						},{
							name : "orderStatus"
						}, {
							name : "payStatus"
						}, {
							name : "payType"
						}, {
							name : "totalAmount"
						}, {
							name : "goodsNumber"
						}, {
							name : "payAmount"
						}, {
							name : "consignee"
						}, {
							name : "consignPhone"
						}, {
							name : "consignAddress"
						}, {
							name : "remark"
						}, {
							name : "payGoodsName"
						}, {
							name : "createdDate"
						}, {
							name : "createdName"
						}, {
							name : "cancelName"
						}, {
							name : 'orderType'
						}, {
							name : 'shipperCodeName'
						},{
							name : 'shipperPhone'
						},{ 
							name: 'shipperCode'
						},{
							name: 'logisticNo'
						}]

			});

	// 取数据store
	var orderToBeSendViewStore = new Ext.data.Store({
				autoLoad : true,// 要加载数据必须设置为true
				proxy : new Ext.data.HttpProxy({
							url : __ctxPath + "/orderVfManager/selectOrdersVf"
						}),
				remoteSort : true,
				baseParams : {
					start : 0,
					limit : 25,
					orderStatus : '1'
				},
				listeners : {
					beforeload : {
						fn : function(thiz, options) {
							Ext.apply(thiz.baseParams, Ext
											.getCmp('queryOrderToBeSendForm')
											.getForm().getValues());
						}
					}
				},
				reader : orderManagerReader
			});
	var orderToBeSendTb = new Ext.Toolbar({// 定义grid的toolbar
		height : 25,
		items : []
	});
	orderToBeSendTb.add(new Ext.scm.Button({
				text : "批量发货",
				width : 80,
				hsValue : 'orderToBeSend_批量发货',
				pressed : true,
				iconCls : "btn-edit",
				handler : function() {
					batchOrderToBeSendUpdateStatus(2, '已发货');
				}
			}));
	orderToBeSendTb.add(new Ext.Toolbar.Spacer());

	orderToBeSendTb.add(new Ext.Toolbar.Spacer());
	orderToBeSendTb.add(new Ext.scm.Button({
				text : "刷 新",
				width : 80,
				iconCls : "btn-refresh",
				hsValue : 'orderToBeSend_刷新',
				pressed : true,
				handler : function() {
					queryOrdersToBeSend();
				}
			}));
	var orderToBeSendManagerGrid = new Ext.grid.GridPanel({
				id : 'orderToBeSendManagerGrid',
				store : orderToBeSendViewStore,
				cm : orderToBeSendCm,
				sm : orderToBeSendSm,
				autoScroll : true,
				loadMask : true,
				stripeRows : true,
				columnLines : true,
				loadMask : {
					msg : "正在加载数据，请稍侯……"
				},
				viewConfig : {
					emptyText : '没有您想要的数据!'
				},
				anchor : '100% 84%',
				frame : true,
				tbar : orderToBeSendTb,
				bbar : new PG.PagingBar({
							id : 'orderToBeSendGridPage',
							store : orderToBeSendViewStore
						})
			});
	return orderToBeSendManagerGrid;
};

// 查询
function queryOrdersToBeSend() {
	if (Ext.getCmp('queryOrderToBeSendForm').getForm().isValid()) {
		var grid = Ext.getCmp('orderToBeSendManagerGrid');
		var store = grid.store;
		var pagesize = Ext.getCmp('orderToBeSendGridPage').pageSize;
		store.load({
					params : {
						start : 0,
						limit : pagesize,
						"orderStatusArray" : '1'
					}
				});
	}
}

/**
 * 订单单个确认
 * 
 * @param {}
 *            orderId
 * @param {}
 *            orderStatus
 * @param {}
 *            statusName
 */
function updateOrderToBeSendStatusOne(orderId, orderStatus, statusName) {
	Ext.Msg.confirm("信息确认", "您确定要将订单状态变更为<span style='color:#F00'>"
					+ statusName + "</span>？", function(c) {
				if (c == "yes") {
					commonOrderToBeSendUpateOrder(orderId, orderStatus,
							statusName);
				}
			});
}
/**
 * 查询订单详情
 * 
 * @param {}
 *            id
 */
function lookOrderToBeSendDetail(id) {
	var centerPanel = App.getContentPanel();
	var tab = centerPanel.getItem(PmsUtil.ORDER_VF_MESSAGE_DETAIL);
	var createNewTab = new CreatNewTab(PmsUtil.ORDER_VF_MESSAGE_DETAIL, '订单详情');
	if (tab == null) {
		createNewTab.createNew(tab);
	} else {
		createNewTab.createOld(tab, ['lookOrderVfDetailFields',
						'lookOrderVfDetailForm', 'lookOrderVfDetailGrid']);
	}
	Ext.Loader.load([__ctxPath + '/js/order_vf/orderVfDetail.js'], function() {
				Ext.getCmp("centerTabPanel").getActiveTab().add(
						lookOrderVfDetailSearch(id), orderVfDetailGrid(id));
				Ext.getCmp("centerTabPanel").getActiveTab().doLayout();
			});
}

/**
 * 批量修改订单状态
 */
function batchOrderToBeSendUpdateStatus(orderStatus, statusName) {
	var d = Ext.getCmp("orderToBeSendManagerGrid");
	var jsonrecord = d.getSelectionModel().getSelections();
	if (jsonrecord.length == 0) {
		Ext.MessageBox.show({
					title : "操作信息",
					msg : "请选择要发货的订单!",
					buttons : Ext.MessageBox.OK,
					icon : Ext.MessageBox.WARNING
				});
		return;
	}
	Ext.Msg.confirm("信息确认", "您确定要将订单状态变更为<span style='color:#F00'>"
					+ statusName + "</span>？", function(c) {
				if (c == "yes") {
					var orderIds = "";
					var m = 0;
					for (var i = 0; i < jsonrecord.length; i++) {
						var tmp = jsonrecord[i];
						if (m > 0) {
							orderIds = orderIds + "," + tmp.data.id;
						} else {
							orderIds = tmp.data.id;
						}
						m++;
					}
					commonOrderToBeSendUpateOrder(orderIds, orderStatus,
							statusName);
				}
			});
}

/**
 * 公用修改订单状态方法
 * 
 * @param {}
 *            orderIds
 * @param {}
 *            orderStatus
 * @param {}
 *            statusName
 */
function commonOrderToBeSendUpateOrder(orderIds, orderStatus, statusName) {
	orderToBeSend.show();
	Ext.Ajax.request({
				url : __ctxPath + "/orderVfManager/updateOrderVfStatus",
				params : {
					orderIds : orderIds,
					orderStatus : orderStatus,
					statusName : statusName,
					cancelReason : ''
				},
				method : "post",
				success : function(response, config) {
					orderToBeSend.hide();
					var jsonData = Ext.util.JSON.decode(response.responseText);
					if (jsonData.success) {
						Ext.MessageBox.show({
									title : "信息提示",
									msg : "修改订单状态成功!",
									buttons : Ext.MessageBox.OK,
									icon : Ext.MessageBox.INFO
								});
						queryOrdersToBeSend();
					} else {
						Ext.MessageBox.show({
									title : "操作信息",
									msg : "修改订单状态失败!",
									buttons : Ext.MessageBox.OK,
									icon : Ext.MessageBox.ERROR
								});
					}
				},
				failure : function(response, config) {
					orderToBeSend.hide();
					Ext.MessageBox.show({
								title : "错误提示",
								msg : "服务器请求异常，请稍后再试!",
								buttons : Ext.MessageBox.OK,
								icon : Ext.MessageBox.ERROR
							});
				}
			});
};

// 修改
function updateOrderToBeSend(orderId) {
	try {
		updateOrderVfWin(orderId, 'orderToBeSendManagerGrid').show();
	} catch (Error) {
		Ext.Loader.load([__ctxPath + '/js/order_vf/orderVfForm.js'], function() {
					updateOrderVfWin(orderId, 'orderToBeSendManagerGrid').show();
				});
	}
}

/**
 * 填写物流单号
 * 
 * @param {}
 *            orderId
 */
function addLogisticNo(orderId) {
	try {
		updateOrderLosgisticVfWin(orderId,'orderToBeSendManagerGrid').show();
	} catch (Error) {
		Ext.Loader.load([__ctxPath + '/js/order_vf/logisticNoVf.js'], function() {
					updateOrderLosgisticVfWin(orderId,'orderToBeSendManagerGrid').show();
				});
	}

}

Ext.getCmp("centerTabPanel").getActiveTab().add(queryOrderToBeSendSearch(),
		orderToBeSendManagerGrid());
Ext.getCmp("centerTabPanel").getActiveTab().doLayout();